package com.fingard.dsp.bank.directbank.gzelink01;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;

import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectUtil;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.bankInterface.IIvrRec;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;

import AvivaCofco.TelTran;

public class GZELINK01IvrRec extends GZELINK01Base implements IIvrRec {
	
	/**
	 * IVR语音扣款提交
	 */
	public RetAtsSingle d_9109_IvrRec(ReqSingle p_req9109) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9109.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		
		try {
			String ivrUrl = bankFront.getUrl("ivr");
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9109.singleDetail.recAct, "ivr");
			if(actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath) || StringHelper.isNullOrEmpty(ivrUrl)){
				String errMsg = "";
				if (actItem == null) {
					errMsg = "未找到账号" + p_req9109.singleDetail.recAct + "的批量商户配置节点；";
				} else if(!FileHelper.existFile(actItem.ownKeyStorePath)){
					errMsg = "账号" + p_req9109.singleDetail.recAct + "的证书文件不存在；";
				}
				if (StringHelper.isNullOrEmpty(ivrUrl)) {
					errMsg += "IVR语音服务地址为空，请检查BankFront中的配置；";
				}
				errMsg = StringHelper.trimEnd(errMsg, "；");
				DirectUtil.FillPaymentFailed(p_req9109.singleDetail, tmpRetDetail, errMsg, FailCode.E9981);
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			else {
				//Convert.ToDecimal(tmpReqDtl.PayAmount).ToString("F2")
				String OrderAmount = Format.DecimalAmtFormat.format(new BigDecimal(p_req9109.singleDetail.payAmount));
				String ivrCharset = getCharset("ivr");
				WriteBankLogLn("ivrCharset:"+ivrCharset);
				String oppAccName = URLEncoder.encode(p_req9109.singleDetail.payName, ivrCharset).toUpperCase();
				String getUrlQryStr = "UserID=" + p_req9109.singleDetail.cellPhone + "&MerID=" + actItem.merchantId + "&PayID=" + p_req9109.singleDetail.askNumber + "&UserPID=" + p_req9109.singleDetail.certNum + "&AccName=" + oppAccName + "&BankCard=" + p_req9109.singleDetail.payAct + "&BankPID=" + p_req9109.singleDetail.certNum + "&OrderAmount=" + OrderAmount + "&Remark=&TransType=14";
                this.WriteBankLogStep2(getUrlQryStr);
                
                
                //获取加密报文
            	TelTran tel=new TelTran();
                String enErrMsg = "";
                boolean tmpEnResult = false;
                try
                {
                    tmpEnResult = tel.EncryptMsg(getUrlQryStr, actItem.ownKeyStorePath);
                    if (!tmpEnResult){
                    	enErrMsg = tel.LastErrMsg;//获取加密失败,提示信息
                    }
                } catch (Exception ex)
                {
                    tmpEnResult = false;
                    enErrMsg = "加密失败：" + ex.getMessage();
                    this.WriteBankLogLn(ex);
                }
                
                if (tmpEnResult)
                {
                    String encryptStr = tel.LastResult;//获取订单通知请求加密串
                    String tmpGetUrl = ivrUrl + "?EncryptMsg=" + encryptStr;
                    this.WriteBankLogLn("提交请求:" + tmpGetUrl);
                    WebRequest tmpWebRequest = new WebRequest(tmpGetUrl);
                    tmpWebRequest.setReadTimeout(this.getReadTimeout());
                    tmpWebRequest.setRequestProperty("connection", "Close");
                    tmpWebRequest.setRequestProperty("Content-Type", "text/xml; charset=" + this.getCharset("ivr"));
                    String[] retStr = tmpWebRequest.upload(null, this.getCharset());
                    if(retStr[0].length() == 0){
                    	
                    	this.WriteBankLogStep3(retStr[1]);
                    	
                    	String bkRetStr = retStr[1].trim();
                    	
                    	tmpRetDetail.respCode = "0";
                    	tmpRetDetail.reqSeqID = p_req9109.singleDetail.askNumber;
                        tmpRetDetail.transState = bkRetStr;
                        tmpRetDetail.payInfoCode = bkRetStr;

                        tmpRetDetail.respInfo = this.getBankConfig().getMapAdvanceValue("IVRMsgMapping", "code", "intro", bkRetStr);
                        if(StringHelper.isNullOrEmpty(tmpRetDetail.respInfo)){
                       	 tmpRetDetail.respInfo = bkRetStr;
                        }
                    }
                    else if(retStr[0].equals(ConnState.FAIL)){
                    	DirectUtil.FillPaymentFailed(p_req9109.singleDetail, tmpRetDetail, retStr[1], FailCode.E9999);
                    }
                    else{
                    	tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = retStr[1];
                    }
                }
                else
                {
                    if (StringHelper.isNullOrEmpty(enErrMsg))
                    {
                    	enErrMsg = "加密失败";
                    }
                    DirectUtil.FillPaymentFailed(p_req9109.singleDetail, tmpRetDetail, enErrMsg, FailCode.E9981);
                }
			}
		} catch (Exception e) {
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = e.getMessage();
			
			WriteBankLogLn2("交互出错，原因如下:\r\n" + LogHelper.getStackTrace(e));
		}
		
		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req9109.singleDetail.askNumber;
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	/**
	 * IVR语音扣款状态查询
	 */
	public RetAtsSingle d_9145_QryIvrRec(ReqQrySingle p_req9145) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9145.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		
		try {
			boolean isChked = true;
			String chkMsg = "";
			String ivrUrl = bankFront.getUrl("ivr");
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9145.recAct, "ivr");
			if(actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath) || StringHelper.isNullOrEmpty(ivrUrl)){
				isChked = false;
				if (actItem == null) {
					chkMsg = "未找到账号" + p_req9145.recAct + "的批量商户配置节点；";
				} else if(!FileHelper.existFile(actItem.ownKeyStorePath)){
					chkMsg = "账号" + p_req9145.recAct + "的证书文件不存在；";
				}
				if (StringHelper.isNullOrEmpty(ivrUrl)) {
					chkMsg += "IVR语音服务地址为空，请检查BankFront中的配置；";
				}
			}
			if (StringHelper.isNullOrEmpty(p_req9145.payAmount))
            {
				isChked = false;
				chkMsg += "查询金额PayAmount不能为空；";
            }
            if (StringHelper.isNullOrEmpty(p_req9145.cellPhone))
            {
            	isChked = false;
                chkMsg += "查询手机号CellPhone或Mobile不能为空；";
            }
			if(isChked){
				String OrderAmount = Format.DecimalAmtFormat.format(new BigDecimal(p_req9145.payAmount));
				String getUrlQryStr = "UserID=" + p_req9145.cellPhone + "&MerID=" + actItem.merchantId + "&PayID=" + p_req9145.askNumber + "&OrderAmount=" + OrderAmount + "&TransType=33";
this.WriteBankLogStep2(getUrlQryStr);
                //获取加密报文
            	TelTran tel=new TelTran();
                String enErrMsg = "";
                boolean tmpEnResult = false;
                try
                {
                    tmpEnResult = tel.EncryptMsg(getUrlQryStr, actItem.ownKeyStorePath);
                    if (!tmpEnResult){
                    	enErrMsg = tel.LastErrMsg;//获取加密失败,提示信息
                    }
                } catch (Exception ex){
                    tmpEnResult = false;
                    enErrMsg = "加密失败：" + ex.getMessage();
                    this.WriteBankLogLn(ex);
                }
                
                if (tmpEnResult){
                	String encryptStr = tel.LastResult;//获取订单通知请求加密串
                    String tmpGetUrl = ivrUrl + "?EncryptMsg=" + encryptStr;
                    this.WriteBankLogLn("提交请求:" + tmpGetUrl);
                    WebRequest tmpWebRequest = new WebRequest(tmpGetUrl);
                    tmpWebRequest.setReadTimeout(this.getReadTimeout());
                    tmpWebRequest.setRequestProperty("connection", "Close");
                    tmpWebRequest.setRequestProperty("Content-Type", "text/xml; charset=" + this.getCharset("ivr"));
                    String[] retStr = tmpWebRequest.upload(null, this.getCharset());
                    if(retStr[0].length() == 0){
                    	this.WriteBankLogStep3(retStr[1]);
                    	String bkEncryptedMsg = retStr[1].trim();
                    	boolean deReuslt = tel.DecryptMsg(bkEncryptedMsg, actItem.ownKeyStorePath);
                    	if(deReuslt){
                    		String plainTxt = tel.LastResult;
                    		WriteBankLogStep3(plainTxt);
                    		HashMap<String,String> map = StringHelper.splitQryString(plainTxt);
                    		if (map.containsKey("RetCode") && map.containsKey("SysCode") && map.containsKey("PayID")){
                    			tmpRetDetail.respCode = "0";
                    			tmpRetDetail.reqSeqID = map.get("PayID");
                                tmpRetDetail.transState = map.get("RetCode") + "+" + map.get("SysCode");
                    			
                                String tmpMapCode = "";
                                if (StringHelper.hasAnyChar(map.get("SysCode")))
                                {
                                    //96 系统故障，请稍后再试
                                    if (map.get("SysCode") == "96")
                                    {
                                        tmpRetDetail.respCode = "-1";
                                    }
                                    tmpRetDetail.payInfoCode = map.get("SysCode");
                                    tmpMapCode = "SysCode_" + tmpRetDetail.payInfoCode;
                                }
                                else
                                {
                                    tmpRetDetail.payInfoCode = map.get("RetCode");
                                    tmpMapCode = "RetCode_" + tmpRetDetail.payInfoCode;
                                }
                                if (map.containsKey("OrderAmount"))
                                {
                                    tmpRetDetail.transAmt = map.get("OrderAmount");
                                }
                                
                                tmpRetDetail.respInfo = this.getBankConfig().getMapAdvanceValue("IVRMsgMapping", "code", "intro", tmpMapCode);

                            }else{
                            	tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = "返回的信息缺少必要字段：RetCode、SysCode、PayID";
                            }
                    	}
                    	else{
                    		tmpRetDetail.respCode = "-1";
                    		tmpRetDetail.respInfo = tel.LastErrMsg;
                    		if(StringHelper.isNullOrEmpty(tmpRetDetail.respInfo)){
                    			tmpRetDetail.respInfo = "解密失败";
                    		}
                    	}
                    }
                    else{
                    	tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = retStr[1];
                    }
                }
                else{
                	tmpRetDetail.respCode = "-1";
    				tmpRetDetail.respInfo = enErrMsg;
                }
			}
			else{
				chkMsg = StringHelper.trimEnd(chkMsg, "；");
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = chkMsg;
			}
		} catch (Exception e) {
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = e.getMessage();
			
			WriteBankLogLn2("交互出错，原因如下:\r\n" + LogHelper.getStackTrace(e));
		}
		
		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req9145.askNumber;
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}
}
